const jsonServer = require("json-server");

const app = jsonServer.create();

const router = jsonServer.router("./db.json");

require("dotenv").config({ path: "./.env" });

const { HOST, PORT, BASE_PATH, DOCS_PATH, M_ACL, M_AUTH } = process.env;

/* 静态目录 */
app.use(jsonServer.defaults({ static: "./public", bodyParser: true }));

/* 初始化 */
require("./middleware/init.middleware")(router.db);

/* swagger */
require("./middleware/expressJSDocSwagger.middleware")(app);

// console.log(M_AUTH, M_ACL);
/* 中间件 鉴权 */
M_AUTH === "1" && app.use(require("./middleware/auth.middleware")());

/* 中间件 权限 */
M_ACL === "1" && app.use(require("./middleware/acl.middleware")(router.db));

/* 统一返回格式 */
router.render = (req, res) => {
  const r = {
    status: res.statusCode,
    success: true,
    data: res.locals.data,
  };
  if (res.statusCode === 404) {
    r.status = "Not Found";
    r.success = false;
    r.message = "Resource not found";
    r.data = "";
  }
  res.send(r);
};
/* 路由 */
app.use(BASE_PATH, [
  require("./routes/login")(router.db),
  require("./routes/users")(),
  // require("./routes/swagger")(),
  router,
]);

/* 统一设置更新时间和添加时间 */
app.use((req, res, next) => {
  if (req.method === "POST") {
    req.body.ctime = Date.now();
    req.body.mtime = Date.now();
  }
  if (req.method === "PUT" || req.method === "PATCH") {
    req.body.mtime = Date.now();
  }
  next();
});

/* 启动服务 */
app.listen(PORT, HOST, () => {
  console.table({
    swagger: `http://${HOST}:${PORT}${BASE_PATH}${DOCS_PATH}`,
  });
});
